import { Dropdown, DropdownItem } from "@/ui/Dropdown/Dropdown";
import cls from "@/styles/components/CreateUser/RoleSelector.module.scss";
import React, { useEffect, useState } from "react";
import { UserI } from "@/models/user";
import { Icon } from "@/ui/Icons/Icon";
import cn from "classnames";
import { useSpecialization, useSpecializationType } from "@/api/specialization";
import { SpecializationI } from "@/models/specialization";

type Props = {
  user: Partial<UserI>;
  updateUser: (v: Partial<UserI>) => void;
  disabled?: boolean;
};

const removeFromArray = (arr: SpecializationI[], value: SpecializationI) => {
  const index = arr.findIndex((item) => item.id === value.id);
  arr.splice(index, 1);
  return [...arr];
};

export const AdditionalSpecSelector = ({
  user,
  updateUser,
  disabled,
}: Props) => {
  const [specDropdownOpen, setSpecDropdownOpen] = useState(false);
  const [selected, setSelected] = useState<SpecializationI[]>([]);

  const [, specData] = useSpecializationType();
  const [isInitialsSet, setIsInitialsSet] = useState(false);

  useEffect(() => {
    if (!selected) return;
    updateUser({
      additional_specializations: selected,
    });
  }, [selected]);

  useEffect(() => {
    if (isInitialsSet || !specData) return;
    if (!user.additional_specializations) {
      setIsInitialsSet(true);
      return;
    }
    setSelected(
      user.additional_specializations.map((s) =>
        specData.find((i) => i.specialization === s.specialization)
      )
    );
    setIsInitialsSet(true);
  }, [user, specData]);

  const updateSelected = (option: SpecializationI) => {
    if (selected.find((s) => s.id === option.id))
      setSelected(removeFromArray(selected, option));
    else setSelected((prev) => [...prev, option]);
  };

  const toggleOpen = () => {
    if (disabled) return;
    setSpecDropdownOpen(!specDropdownOpen);
  };

  return (
    <div className={cls.root}>
      <div className={cls.label}>Дополнительные модальности</div>
      <div
        className={cn(cls.valueBox, { [cls.disabled]: disabled })}
        onClick={() => toggleOpen()}
      >
        <div className={cls.value}>
          {selected
            .map((s) => {
              return s.specialization;
            })
            .join(", ")}
        </div>
        <button
          type="button"
          onClick={() => toggleOpen()}
          className={cls.arrow}
        >
          <Icon name="arrow" />
        </button>
      </div>
      <Dropdown
        isOpen={specDropdownOpen}
        close={() => setSpecDropdownOpen(false)}
        parentCls={cls.root}
        fullWidth
      >
        {specData?.map((o) => {
          return (
            <DropdownItem key={o.id}>
              <button
                type="button"
                className={cn(cls.option, {
                  [cls.selected]: selected.find((s) => s.id === o.id),
                })}
                onClick={() => {
                  updateSelected(o);
                  setSpecDropdownOpen(false);
                }}
              >
                {o.specialization}
              </button>
            </DropdownItem>
          );
        })}
      </Dropdown>
    </div>
  );
};
